package com.captjack.micro.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.LongAdder;

/**
 * @author Capt Jack
 * @date 2018/7/6
 */
@Component
public class CustomizeHessianFilter implements GlobalFilter {

    /**
     *
     */
    private final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");

    /**
     * 计数，统计访问量
     */
    private final LongAdder allRequestCount = new LongAdder();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        allRequestCount.increment();
        return chain.filter(exchange);
    }

    public CustomizeHessianFilter() {
        Executors.newSingleThreadExecutor().execute(() -> {
            try {
                while (true) {
                    System.out.println(simpleDateFormat.format(new Date()) + " 当前请求总量： " + allRequestCount.longValue());
                    Thread.sleep(10000L);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }

}
